import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import { Card, Typography, Spin, Alert, Flex, Avatar, List, Divider } from 'antd';

const { Title, Text } = Typography;

interface CircleDetail {
    id: number;
    name: string;
    description: string;
    avatar?: string;
    coverImage?: string;
    creatorId: number;
    memberCount: number;
    postCount: number;
    isPrivate: boolean;
    members?: { id: number; username: string; avatar?: string }[];
    tags?: { id: number; name: string }[];
}

interface Member {
    id: number;
    username: string;
    avatar?: string;
}

interface CirclePost {
    id: number;
    content: string;
    images?: string[] | null;
    authorId: number;
    circleId: number;
    likeCount: number;
    commentCount: number;
    isTop: boolean;
    isEssence: boolean;
    createdAt?: Date;
    updatedAt?: Date;
    author?: { id: number; username: string; avatar?: string };
}

const CircleDetailPage: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const [circle, setCircle] = useState<CircleDetail | null>(null);
    const [members, setMembers] = useState<Member[]>([]);
    const [posts, setPosts] = useState<CirclePost[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);
    const [membersLoading, setMembersLoading] = useState<boolean>(false);
    const [membersError, setMembersError] = useState<string | null>(null);
    const [postsLoading, setPostsLoading] = useState<boolean>(false);
    const [postsError, setPostsError] = useState<string | null>(null);

    useEffect(() => {
        const fetchCircleDetail = async () => {
            try {
                // TODO: 根据实际后端地址修改 baseURL
                const response = await axios.get(`/api/circles/${id}`);
                setCircle(response.data);
            } catch (err) {
                setError('加载圈子详情失败');
                console.error('获取圈子详情失败:', err);
            } finally {
                setLoading(false);
            }
        };

        if (id) {
            fetchCircleDetail();
        }
    }, [id]);

    useEffect(() => {
        const fetchMembers = async () => {
            if (!id) return;
            setMembersLoading(true);
            try {
                // TODO: 根据实际后端地址修改 baseURL
                const response = await axios.get(`/api/circles/${id}/members`);
                setMembers(response.data.members);
            } catch (err) {
                setMembersError('加载成员列表失败');
                console.error('获取成员列表失败:', err);
            } finally {
                setMembersLoading(false);
            }
        };

        if (circle) {
            fetchMembers();
        }
    }, [circle, id]);

    useEffect(() => {
        const fetchPosts = async () => {
            if (!id) return;
            setPostsLoading(true);
            try {
                // TODO: 根据实际后端地址修改 baseURL
                const response = await axios.get(`/api/circles/${id}/posts`);
                setPosts(response.data.posts);
            } catch (err) {
                setPostsError('加载帖子列表失败');
                console.error('获取帖子列表失败:', err);
            } finally {
                setPostsLoading(false);
            }
        };

        if (circle) {
            fetchPosts();
        }
    }, [circle, id]);

    if (loading) {
        return <Spin></Spin>;
    }

    if (error) {
        return <Alert message={error} type="error" />;
    }

    if (!circle) {
        return <Alert message="未找到圈子" type="warning" />;
    }

    return (
        <div style={{ padding: '20px' }}>
            <Card
                cover={circle.coverImage ? <img alt="cover" src={circle.coverImage} /> : null}
            >
                <Title level={2}>{circle.name}</Title>
                <Text>{circle.description}</Text>
                <p>创建者 ID: {circle.creatorId}</p>
                <p>成员数: {circle.memberCount}</p>
                <p>帖子数: {circle.postCount}</p>
                <p>是否私有: {circle.isPrivate ? '是' : '否'}</p>

                {circle.tags && circle.tags.length > 0 && (
                    <>
                        <Title level={4}>标签:</Title>
                        <Flex wrap="wrap" gap="small">
                            {circle.tags.map(tag => (
                                <Text key={tag.id} type="secondary">{tag.name}</Text>
                            ))}
                        </Flex>
                    </>
                )}

                <Divider />

                <Title level={4}>成员:</Title>
                {membersLoading ? (
                    <Spin size="small" />
                ) : membersError ? (
                    <Alert message={membersError} type="error" />
                ) : members && members.length > 0 ? (
                    <List
                        dataSource={members}
                        renderItem={member => (
                            <List.Item key={member.id}>
                                <List.Item.Meta
                                    avatar={<Avatar src={member.avatar} />}
                                    title={member.username}
                                />
                            </List.Item>
                        )}
                    />
                ) : (
                    <Text type="secondary">暂无成员</Text>
                )}

                <Divider />

                <Title level={4}>帖子:</Title>
                {postsLoading ? (
                    <Spin size="small" />
                ) : postsError ? (
                    <Alert message={postsError} type="error" />
                ) : posts && posts.length > 0 ? (
                    <List
                        dataSource={posts}
                        renderItem={post => (
                            <List.Item key={post.id}>
                                <Card size="small" style={{ width: '100%' }}>
                                    <List.Item.Meta
                                        avatar={post.author?.avatar ? <Avatar src={post.author.avatar} /> : <Avatar>{post.author?.username[0]}</Avatar>}
                                        title={post.author?.username}
                                        description={post.createdAt ? new Date(post.createdAt).toLocaleString() : ''}
                                    />
                                    <Text>{post.content}</Text>
                                    <p>点赞数: {post.likeCount}</p>
                                    <p>评论数: {post.commentCount}</p>
                                </Card>
                            </List.Item>
                        )}
                    />
                ) : (
                    <Text type="secondary">暂无帖子</Text>
                )}

            </Card>
        </div>
    );
};

export default CircleDetailPage; 